package com.hspedu.polymorphic_.polyarr;

/**
 * 现有一个继承结构如下：要求创建1个Person对象，
 * 2个Student对象和2个Teacher对象，
 * 统一放在数组中，并调用每个对象say方法
 */
public class PloyArray {
    public static void main(String[] args) {
        Person[] persons = new Person[5];
        persons[0] = new Person("jack", 20);
        persons[1] = new Student("marry", 18, 100);
        persons[2] = new Student("smith", 19,30.1);
        persons[3] = new Teacher("scott", 30,20000);
        persons[4] = new Teacher("kim", 50,25000);

        //循环遍历多态数组，调用say
        for (int i = 0; i < persons.length; i++) {
            //person[i],编译类型是Person，运行类型是根据实际情况由JVM来判断
            System.out.println(persons[i].say());//动态绑定机制

//            persons[i].study//不能这样调用

            //使用 类型判断 + 向下转型
            if (persons[i] instanceof Student){
//                ((Student)persons[i]).study();//向下转型1
                Student student = (Student)persons[i];//向下转型2
                student.study();
            }else if (persons[i] instanceof Teacher){
                ((Teacher)persons[i]).teach();
            }else{
                System.out.println("你的类型有无，请仔细检查");
            }
        }
    }
}
